﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.IO.Compression;

using MySql.Data.MySqlClient;
using System.IO;
using System.Threading;

namespace inserterDb
{
    [RunInstaller(true)]
    public partial class Installer1 : System.Configuration.Install.Installer
    {
        public Installer1()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            base.Install(stateSaver);

            InsertMySql();
            //CreatDataBase();
            Log("安装成功！");
        }

        //安装mysql
        protected void InsertMySql()
        {
            //通过log记录地址
            string physicalRoot = this.Context.Parameters["targetdir"]; // 安装物理路径 C:\program\microp
            physicalRoot = physicalRoot.TrimEnd('\\');
            string filePath = physicalRoot + "dir.txt";
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            File.WriteAllText(filePath, physicalRoot);



            //解压缩
            string zipFilePath = physicalRoot + "\\MySQL Server 5.5.zip";
            string extractPath = physicalRoot + "\\";

            try
            {
                if (File.Exists(zipFilePath))
                {
                    // 如果目标文件夹不存在则创建
                    if (!Directory.Exists(extractPath))
                    {
                        Directory.CreateDirectory(extractPath);
                    }

                    // 解压缩文件
                    ZipFile.ExtractToDirectory(zipFilePath, extractPath);
                    Log("文件解压缩完成。");
                }
                else
                {
                    Log("ZIP 文件不存在。");
                }
            }
            catch (Exception ex)
            {
                Log($"解压缩过程中出现错误: {ex.Message}");
            }


            //physicalRoot = physicalRoot.Remove(physicalRoot.Length - 1);
            Log($"physicalRoot:{physicalRoot}");
            string appPath = physicalRoot + "\\MySQL Server 5.5\\";
            Log($"appPath:{appPath}");
            //string appPath = physicalRoot + "\\MySQL Server 5.5\\";
            //appPath = "D:\\MySQL\\MySQL Server 5.5\\";

            //1.修改my.ini配置  为防止本机已装mysql，特修改my.ini中端口号为3307
            //string iniFile = File.ReadAllText(appPath + "my.ini");
            //iniFile = iniFile.Replace("%BaseDir%", physicalRoot.Replace("\\", "/")); //%BaseDir%为my.ini中自定义的目录参数
            //File.WriteAllText(appPath + "my.ini", iniFile);

            Log("创建win服务……");
            //2.创建win服务
            string command1 = " install MySQL80 --defaults-file=\"" + appPath + "my.ini\"";
            string info1 = CommandHelper.Execute(appPath + "bin\\mysqld.exe", command1, 0);
            //string info1 = CommandHelper.Execute(appPath + "bin\\mysqld.exe", " install MySQL80 --defaults-file=\"" + appPath + "my.ini\"", 0);
            Log($"command1:{command1}");
            Log(info1);
            Thread.Sleep(3000);
            Log("使用net start启动服务");
            //3.启动服务
            string info2 = CommandHelper.Execute("net start MySQL80", 0);
            Log(info2);

            Log("启动服务完成!");
            Thread.Sleep(5000);
            MySqlConnection con = new MySqlConnection("Data Source='localhost';Port='3307';Database='';User Id='root';Password='';");
            try
            {
                con.Open();
                con.Close();
                Log("连接成功！");
            }
            catch (Exception ex)
            {
                Log("连接失败！" + ex.Message);
            }


        }
        //创建数据库并初始化表
        protected void CreatDataBase()
        {
            string physicalRoot = this.Context.Parameters["targetdir"]; // 安装物理路径 C:\program\microp
            string mysqlcon = "Data Source='localhost';Port='3307';Database='{0}';User Id='root';Password='';";

            MySqlConnection conn = new MySqlConnection(string.Format(mysqlcon, ""));
            FileInfo file = new FileInfo(physicalRoot + "\\DBInit\\yourDB.sql");  //filename是sql脚本文件路径。
            string sql = file.OpenText().ReadToEnd();

            try
            {
                MySqlScript script = new MySqlScript(conn);
                script.Query = sql;
                int count = script.Execute();
                Log("数据库初始化完成！");

                MySqlConnection con2 = new MySqlConnection(string.Format(mysqlcon, "yourDB"));
                con2.Open();
                MySqlCommand dbcom = new MySqlCommand("select count(*) from t_image", con2);
                dbcom.ExecuteScalar();
                con2.Close();
                Log("数据库创建OK！");

                //修改config.xml中的数据库链接地址

            }
            catch (Exception ex2)
            {
                Log("数据库创建失败！" + ex2.Message);
            }


        }

        //写日志
        protected void Log(string line)
        {
            string physicalRoot = this.Context.Parameters["targetdir"]; // 安装物理路径 C:\program\microp
            string filePath = physicalRoot + "Install_log.txt";
            if (File.Exists(filePath))
            {
                File.AppendAllLines(filePath, new string[] { DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss] ") + line });
            }
            else
            {
                File.WriteAllLines(filePath, new string[] { DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss] ") + line });
            }
        }
    }
}
